package com.wanban.txplayertest

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.Button
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.wanban.downloader.MultiDownloadManager
import com.wanban.downloader.db.DatabaseUtils
import com.wanban.downloader.db.DownloadEntity
import com.wanban.downloader.model.DownloadParams
import com.wanban.downloader.model.Status
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


class MainActivity: AppCompatActivity() {


    private lateinit var btnStopAll: Button
    private lateinit var btnResumeAll: Button
    private lateinit var btnDeleteAll: Button
    private lateinit var btnDownloadAll: Button
    private lateinit var recyclerView: RecyclerView

    private val downloadingAdapter by lazy { DownloadingAdapter(DataUtils.initDownloadData()) }
    //创建 player 对象
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.layout_activity)
        EventBus.getDefault().register(this)
        btnStopAll = findViewById(R.id.btnStopAll)
        btnResumeAll = findViewById(R.id.btnResumeAll)
        btnDownloadAll = findViewById(R.id.btnDownloadAll)
        btnDeleteAll = findViewById(R.id.btnDeleteAll)
        recyclerView = findViewById(R.id.recycler_downloading)
        recyclerView.itemAnimator = null
        recyclerView.layoutManager = LinearLayoutManager(this)
        recyclerView.adapter = downloadingAdapter

        // 回复数据状态
        MultiDownloadManager.getAllDownloadTasks { tasks ->
            if (tasks.isEmpty()) return@getAllDownloadTasks
            tasks.forEach {
                if (it.state == Status.PREPARE || it.state == Status.START || it.state == Status.DOWNLOADING
                    || (it.state == Status.ERROR && it.retryTime < DownloadParams.maxRetryTimes)) {
                    // 重置下载状态
                    it.state = Status.PENDING
                }
            }

            downloadingAdapter.data.forEach {
                for (task in tasks) {
                    if (it.url == task.url) {
                        it.state = task.state
                        it.speed = task.speed
                        it.percent = task.percent
                        it.errorMsg = task.errorMsg
                        it.filePath = task.filePath
                        it.retryTime = task.retryTime
                        it.contentLength = task.contentLength
                        break
                    }
                }
            }
            downloadingAdapter.setList(downloadingAdapter.data)
        }

        downloadingAdapter.setOnItemClickListener { _, _, position ->
            val item = downloadingAdapter.getItemOrNull(position)?:return@setOnItemClickListener
            if (item.state == Status.SUCCESS) {
                val task = DatabaseUtils.getTaskByUrl(item.url)
                val intent = Intent(this@MainActivity, VideoPlayerActivity::class.java)
                intent.putExtra("task", task)
                startActivity(intent)
                return@setOnItemClickListener
            }
            val task = DatabaseUtils.getTaskByUrl(item.url)
            if (task == null) {
                MultiDownloadManager.startDownload(item)
            } else {
                if (task.state == Status.SUCCESS) return@setOnItemClickListener
                if (MultiDownloadManager.isTaskRunning(item.url)) {
                    MultiDownloadManager.stopDownload(item.url)
                } else {
                    MultiDownloadManager.resumeDownload(item.url)
                }
            }
        }

        downloadingAdapter.setOnItemLongClickListener { _, _, position ->
            val item = downloadingAdapter.getItemOrNull(position)?:return@setOnItemLongClickListener false
            val alertDialog = AlertDialog.Builder(this)
            alertDialog.setTitle("提示")
            alertDialog.setMessage("确定要删除当前下载吗？")
            alertDialog.setPositiveButton("确认") { _, _ ->
                MultiDownloadManager.deleteDownload(item.url)
            }
            alertDialog.setNegativeButton("取消") { _, _ -> }
            alertDialog.show()
            return@setOnItemLongClickListener true
        }

        btnStopAll.setOnClickListener {
            MultiDownloadManager.stopAllDownload()
        }

        btnResumeAll.setOnClickListener {
            MultiDownloadManager.resumeAllDownload()
        }

        btnDeleteAll.setOnClickListener {
            val alertDialog = AlertDialog.Builder(this)
            alertDialog.setTitle("提示")
            alertDialog.setMessage("确定要删除所有下载吗？")
            alertDialog.setPositiveButton("确认") { _, _ ->
                MultiDownloadManager.getAllDownloadTasks {
                    it.forEach {
                        MultiDownloadManager.deleteDownload(it.url)
                    }
                }
                downloadingAdapter.data.forEach { it.state = Status.IDLE }
                downloadingAdapter.notifyDataSetChanged()
            }
            alertDialog.setNegativeButton("取消") { _, _ -> }
            alertDialog.show()
        }

        btnDownloadAll.setOnClickListener {
            downloadingAdapter.data.forEach {
                if (it.state != Status.IDLE) return@setOnClickListener
                MultiDownloadManager.startDownload(it)
            }
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onDownloadEvent(event: DownloadEntity){
        // 其他状态，根据当前的状态来改变ui
        val index = downloadingAdapter.data.indexOfFirst { it.url == event.url }
        if (index < 0) return
        val item = downloadingAdapter.getItemOrNull(index)?:return
        item.state = event.state
        item.speed = event.speed
        item.percent = event.percent
        item.errorMsg = event.errorMsg
        item.retryTime = event.retryTime
        item.contentLength = event.contentLength
        downloadingAdapter.notifyItemChanged(index)
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

 }